package com.lemon.smartsafetynew.ui.fragment.user.register;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.lemon.android.http.AesEncryptor;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.entity.common.AreaVo;
import com.lemon.smartsafety.entity.event.common.AreaSelectEvent;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.listener.AreaType;
import com.lemon.smartsafety.ui.activity.common.AreaProvinceActivity;
import com.lemon.smartsafetynew.ui.fragment.base.BaseFragment;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafetynew.entity.User;
import com.lemon.smartsafetynew.entity.event.user.PageEvent;
import com.lemon.smartsafetynew.net.services.AccountServices;
import com.lemon.smartsafetynew.util.common.AppSharePreferenceUtil;
import com.lemon.smartsafetynew.util.constants.KeyConstants;
import com.lemon.smartsafetynew.util.constants.SafeCloudConstants;

import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by Andrew on 2017/7/18.
 */

public class UserRegisterStepThreeFragment extends BaseFragment {

    @Bind(R.id.user_name_edit)
    EditText userNameEdit;
    @Bind(R.id.user_name_error_info_tv)
    TextView userNameErrorInfoTv;
    @Bind(R.id.password_edit)
    EditText passwordEdit;
    @Bind(R.id.eye_imageView)
    ImageView eyeImageView;
    @Bind(R.id.password_error_info_tv)
    TextView passwordErrorInfoTv;
    @Bind(R.id.region_edit)
    TextView regionEdit;
    @Bind(R.id.region_error_info_tv)
    TextView regionErrorInfoTv;

    private MaterialDialog materialDialog;
    private AreaVo areaProvince;
    private AreaVo areaCity;

    @Override
    protected void getBaseArguments() {

    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_user_register_step_three;
    }

    @Override
    protected void initViews() {

        eyeImageView.setSelected(false);

        userNameEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                userNameErrorInfoTv.setText("");
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        passwordEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                passwordErrorInfoTv.setText("");
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    @OnClick({R.id.eye_imageView, R.id.region_layout, R.id.next_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.eye_imageView:

                eyeImageView.setSelected(!eyeImageView.isSelected());
                if (eyeImageView.isSelected()) {
                    passwordEdit.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    passwordEdit.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }

                break;
            case R.id.region_layout:

                Bundle bundle = new Bundle();
                bundle.putBoolean(BundleKey.IS_FOR_REGISTER, true);
                UIHelper.showActivity(getActivity(), bundle, AreaProvinceActivity.class);

                break;
            case R.id.next_btn:

                String userName = userNameEdit.getText().toString().trim();
                String password = passwordEdit.getText().toString().trim();

                if (checkUserName(userName) && matcherUserName(userName)) {

                    if (checkPassword(password) && matcherPassword(password)) {

                        if (checkRegion()) {

                            HashMap<String, String> hashMap = new HashMap<>();
                            hashMap.put("userName", userName);
                            hashMap.put("passWord", AesEncryptor.encrypt(password));
                            hashMap.put("cityId", areaCity.getVoId());
                            hashMap.put("provinceId", areaProvince.getVoId());
                            hashMap.put("mobile", AppSharePreferenceUtil.getInstance().getString(SafeCloudConstants.USER_TELEPHONE_NUMBER, ""));

                            AccountServices.init().registerUser(hashMap);

                        } else {
                            regionErrorInfoTv.setText(getString(R.string.regin_empty_error));
                        }

                    } else {
                        passwordErrorInfoTv.setText(getString(R.string.password_format_error));
                    }

                } else {
                    userNameErrorInfoTv.setText(getString(R.string.user_name_format_error));
                }

                break;
        }
    }

    private boolean checkPassword(String password) {
        return !(null == password || "".equals(password));
    }

    private boolean matcherPassword(String password) {

        String pattern = "^[A-Za-z0-9]{6,25}$";
        Pattern mPattern = Pattern.compile(pattern);
        Matcher mMatcher = mPattern.matcher(password);

        return mMatcher.matches();
    }

    private boolean checkUserName(String userName) {
        return !(null == userName || "".equals(userName));
    }

    private boolean matcherUserName(String userName) {

        String pattern = "^[\\u4e00-\\u9fa5A-Za-z0-9]{2,12}$";
        Pattern mPattern = Pattern.compile(pattern);
        Matcher mMatcher = mPattern.matcher(userName);

        return mMatcher.matches();
    }

    private boolean checkRegion() {
        return areaCity != null && areaProvince != null;
    }

    @Subscribe
    public void onEventMainThread(AreaSelectEvent event) {
        if (AreaType.PROVINCE == event.getType()) {
            areaProvince = event.getData();
        } else if (AreaType.CITY == event.getType()) {
            areaCity = event.getData();
        }
        setAreaViewValue();
    }

    @Subscribe
    public void onEventMainThread(HttpCallbackEvent<User> event) {
        if (KeyConstants.URL_REGISTER_ACCOUNT.equals(event.getTag())) {
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                showDialog();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                cancelDialog();
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    Toast.makeText(getmContext(), "注册成功", Toast.LENGTH_SHORT).show();
                    AppSharePreferenceUtil.getInstance().putString(SafeCloudConstants.CURRENT_USER, new Gson().toJson(event.getObj()));
                    AppService.getBus().post(new PageEvent());
                } else {
                    Toast.makeText(getmContext(), event.getMsg(), Toast.LENGTH_SHORT).show();
                    //regionErrorInfoTv.setText(event.getMsg());
                }
            }
        }

    }

    private void setAreaViewValue() {
        if (areaProvince != null && areaCity != null) {
            String formatString = "%s-%s";
            regionEdit.setText(String.format(formatString, StringUtils.nullValue(areaProvince.getTitle()), StringUtils.nullValue(areaCity.getTitle())));
        } else if (areaProvince != null && areaCity == null) {
            regionEdit.setText(StringUtils.nullValue(areaProvince.getTitle()));
        }
    }

    private void showDialog() {
        materialDialog = new MaterialDialog.Builder(getActivity())
                .content(R.string.please_wait)
                .progress(true, 0)
                .cancelable(false)
                .show();
    }

    private void cancelDialog() {
        if(materialDialog != null && materialDialog.isShowing()) {
            materialDialog.dismiss();
            materialDialog = null;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        cancelDialog();
    }
}
